package club.xshiwu.springcloud.controller;

import club.xshiwu.springcloud.entities.CommonResult;
import club.xshiwu.springcloud.entities.Payment;
import club.xshiwu.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
public class PaymentController {
    @Autowired
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverport;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping(value = "/payment/create")
    public CommonResult<Payment> create(Payment payment) {
        int resoult = paymentService.create(payment);
        if (resoult > 0) {
            return new CommonResult(200, "插入成功" + payment + "端口为" + serverport);
        } else {
            return new CommonResult(444, "插入失败", null);
        }
    }

    @GetMapping(value = "/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);

        if (payment != null) {
            return new CommonResult(200, "查询成功: ，端口为：【" + serverport + "】" + payment);
        } else {
            return new CommonResult(444, "没有对应记录,查询ID: " + id, null);
        }
    }

    @GetMapping(value = "/payment/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            System.out.println(service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            // CLOUD-PAYMENT-SERVICE	192.168.137.1	8006	http://192.168.137.1:8006
            // CLOUD-PAYMENT-SERVICE	192.168.137.1	8005	http://192.168.137.1:8005
            System.out.println(instance.getServiceId()
                    + "\t" + instance.getHost()
                    + "\t" + instance.getPort()
                    + "\t" + instance.getUri()
            );
        }
        return this.discoveryClient;
    }


    @GetMapping("/payment/lb")
    public String getPaymentLB(){
        return serverport;
    }
    @GetMapping("/payment/feign/timeout")
    public String paymentFeignTimeout() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverport;
    }
}
